package com.itheima.login;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//过滤hack.html页面，需要登陆了才能访问
@WebFilter("/hack.html")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //从Session中获取数据
        User user =(User) request.getSession().getAttribute("user");
        //如果user不为null说明登录了
        if (user != null){
            //放行
            chain.doFilter(request, response);
        }else {
            //没有登录，跳转到登录页面
            response.sendRedirect("/login.html");
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}